/**
 * 
 */
package com.ld.admin.controller.oa.work;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ld.admin.controller.AdminBasicController;
import com.ld.admin.model.oa.work.SysUserRelationModel;
import com.ld.admin.model.system.SystemUser;
import com.ld.admin.service.user.UserService;
import com.ld.shieldsb.annotation.Transaction;
import com.ld.shieldsb.annotation.duplicate.SubmitRequestException;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.reflect.ClassUtil;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.web.StaticParams;
import com.ld.shieldsb.common.web.model.SysUser;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.dao.model.QueryModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 *
 * @ClassName UserRelationController
 * @author <a href="mailto:1769975326@qq.com" target="_blank">黄升军</a>
 * @date 2019年8月8日上午8:09:10
 */
@Api(tags = "上下级关系管理")
@Controller(value = "OaWorkUserRelationController")
@RequestMapping("${shieldsb.adminPath}/oa/work/userRelation")
public class UserRelationController extends AdminBasicController<SystemUser> {

    @Autowired
    protected UserService userService;

    @ApiOperation(value = "首页", notes = "")
    @RequestMapping(path = "", method = RequestMethod.GET)
    public String index() {
        return "forward:" + adminPath + "/oa/work/userRelation/toSearch"; // 跳转搜索页面
    }

    @ApiOperation(value = "到搜索页面", notes = "")
    @RequestMapping(path = "/toSearch", method = RequestMethod.GET)
    public String toSearch() {
        return "a/oa/work/userrelation/userrelation_search";
    }

    @ApiOperation(value = "搜索结果", notes = "")
    @RequestMapping(path = "/search", method = RequestMethod.POST)
    public String search() {
        QueryModel queryModel = userService.getSearchQueryModel(request);
        queryModel.addEq("state", StaticParams.STATE_NORMAL);
        userService.getPageBean(request, getModelClass(), queryModel);
        return "a/oa/work/userrelation/userrelation_list";
    }

    @ApiOperation(value = "到用户上下级页面", notes = "")
    @RequestMapping(path = "/tosupervisor_search", method = RequestMethod.GET)
    public String tosupervisor_search() {
        setAttributes();
        Long userId = getLong("id");
        userService.getOne(request, SysUser.class, userId);
        int type = getInt("type");
        QueryModel queryRelationModel = new QueryModel();
        if (type == 0) // 用户上级
        {
            queryRelationModel.addEq("userId", userId);
            queryRelationModel.addQueryField(SysUserRelationModel::getSupervisor);
            basicService.getListAndLinks(request, SysUserRelationModel.class, queryRelationModel);
        } else // 用户下级
        {
            queryRelationModel.addEq("superId", userId);
            queryRelationModel.addQueryField(SysUserRelationModel::getSubordinates);
            basicService.getListAndLinks(request, SysUserRelationModel.class, queryRelationModel);
        }

        return "a/oa/work/userrelation/userrelation_supervisor_search";
    }

    /**
     * 
     * 跳转到获取用户上下级
     * 
     * @Title supervisor_search
     * @author 刘金浩
     * @date 2019年8月16日 下午3:15:56
     * @return String
     */
    @ApiOperation(value = "查询用户上级", notes = "")
    @RequestMapping(path = "/supervisor_search", method = RequestMethod.POST)
    public String supervisor_search() {
        setAttributes();
        QueryModel queryModel = userService.getSearchQueryModel(request);
        queryModel.addEq("state", StaticParams.STATE_NORMAL);
        int pageNum = getInt("p");
        userService.getPageBean(request, getModelClass(), queryModel, pageNum, 10);

        return "a/oa/work/userrelation/userrelation_supervisor";
    }

    /**
     * 
     * 保存用户的上下级
     * 
     * @Title saveSupervisor
     * @author 刘金浩
     * @date 2019年8月16日 下午3:14:01
     * @return
     * @throws SubmitRequestException
     *             Object
     */
    @ApiOperation(value = "用户上下级", notes = "")
    @RequestMapping(path = "/saveSupervisor", method = RequestMethod.POST)
    // 返回json格式
    @ResponseBody
    @Transaction(value = "saveSupervisorTransaction")
    public Object saveSupervisor() throws SubmitRequestException {
        Class<?> declaringType = this.getClass().getSuperclass();
        String clssSimpleName = declaringType.getSimpleName();
        String resource = declaringType.getResource(clssSimpleName + ".class").getFile();
        System.out.println(resource);
        Result result = new Result();
        String relationIds = getString("relationIds");
        Long userId = getLong("userId");
        Long type = getLong("type");// 获取用户上级类型
        if (type == 0) // 用户上级
        {
            // 全删全增，删除用户的上级
            QueryModel queryModel = new QueryModel();
            queryModel.addEq("userId", userId);
            Long count = basicService.getCount(SysUserRelationModel.class, queryModel);
            if (count > 0) { // 判断是否有用户上级，有就删除
                result = basicService.del(SysUserRelationModel.class, "userId", userId);
            } else {
                result.setSuccess(true);
            }
            // 批量增加用户上级
            if (result.getSuccess() && StringUtils.isNotEmpty(relationIds)) {
                String[] relationIdsArr = relationIds.split(",");
                for (int i = 0; i < relationIdsArr.length; i++) {
                    SysUserRelationModel relation = new SysUserRelationModel();
                    relation.setSuperId(ClassUtil.obj2long(relationIdsArr[i]));
                    relation.setUserId(userId);
                    relation.setState(StaticParams.STATE_NORMAL);
                    basicService.addOrUpdate(relation, false);
                }
                result.setSuccess(true);
                result.setMessage("添加上级成功！");
            } else {
                result.setMessage("添加上级失败！");
            }
        } else { // 用户下级

            // 全删全增，删除用户的下级
            QueryModel queryModel = new QueryModel();
            queryModel.addEq("superId", userId);
            Long count = basicService.getCount(SysUserRelationModel.class, queryModel);
            if (count > 0) { // 判断是否有用户下级，有就删除
                result = basicService.del(SysUserRelationModel.class, "superId", userId);
            } else {
                result.setSuccess(true);
            }
            // 批量增加用户下级
            if (result.getSuccess() && StringUtils.isNotEmpty(relationIds)) {
                String[] relationIdsArr = relationIds.split(",");
                for (int i = 0; i < relationIdsArr.length; i++) {
                    SysUserRelationModel relation = new SysUserRelationModel();
                    relation.setSuperId(userId);
                    relation.setUserId(ClassUtil.obj2long(relationIdsArr[i]));
                    relation.setState(StaticParams.STATE_NORMAL);
                    basicService.addOrUpdate(relation, false);
                }
                result.setSuccess(true);
                result.setMessage("添加下级成功！");
            } else {
                result.setMessage("添加下级失败！");
            }
        }

        return Web.Response.result(result);
    }

}
